/**
 * 用队列维护节点遍历的顺序，队列先进先出（FIFO）符合一层一层遍历的逻辑
 * @function {queue}
*/

const levelOrder = root => {
  const res = [],
    queue = []
  if (!root) return res
  queue.push(root)
  while (queue.length) {
    let len = queue.length // 记录当前层级点数
    const curArr = []
    for (let i = 0; i < len; i++) {
      const node = queue.shift()
      curArr.push(node.val)

      // 存放下一级节点
      node.left && queue.push(node.left)
      node.right && queue.push(node.right)
    }
    res.push(curArr)
  }
  return res
}

const root = {
  val: 3,
  left: {
    val: 9,
    left: null,
    right: null
  },
  right: {
    val: 20,
    left: {
      val: 15,
      left: null,
      right: null
    },
    right: {
      val: 7,
      left: null,
      right: null
    }
  }
}

console.log(levelOrder(root));